<template>
	<div class="matchmaker">
		<main class="my_swiper_box">
			<swiper
				class="my_swiper"
				direction="vertical"
				:spaceBetween="15"
				:modules="[Virtual]"
				virtual
				@slideChange="onSlideChange"
			>
				<template v-for="(item, index) of state.menberList" :key="item.id">
					<swiper-slide class="swipe_item">
						<!-- 视频 -->
						<MyVideoPlay2
							:ref="(el) => setItemRef(el, item.id)"
							:item="item"
              :page="state.module"
							@videoClick="videoClick()"
						/>
						<!-- 用户信息 -->
						<div class="user_info">
              <div><span>{{ item.title }}</span></div>
              <div style="font-size: 12px;margin-top: 15px"><span>{{ item.add_time }}</span></div>
            </div>

						<!-- 收藏 -->
						<div class="share collection" v-debounce="() => collect(item.id, index)">
							<img v-if="item.is_collect" src="@/assets/img/video/collectionActive_icon.png" />
							<img v-else src="@/assets/img/video/collection_icon.png" />
							<span>{{item.like_num}}</span>
						</div>
						<!-- 分享 -->
						<div class="share" @click="state.codeDialogShow = true">
							<img src="@/assets/img/video/share_icon.png" />
							<span></span>
						</div>
						<!-- 电话 -->
						<a class="tel" :href="state.mobile" v-debounce="() => callMobile(item.mobile)">
							<img src="@/assets/img/tel_icon.png" />
						</a>
            <span class="tel_bottom_text">报名</span>
					</swiper-slide>
				</template>
			</swiper>
		</main>
		<MyTabbar />

    <!-- 分享说明 -->
    <MyDialogBtn v-model:show="state.codeDialogShow" column>
      <template #content>
        <div style="max-height: 50vh; overflow: scroll">
          <div style="margin-bottom: 30px">分享说明</div>
          <p v-html="state.promote_contents" style="font-size: 13px; text-align: left; line-height: 24px"></p>
        </div>
      </template>
      <template #btn>
        <van-button type="primary" @click="state.codeDialogShow = false">确定</van-button>
      </template>
    </MyDialogBtn>
	</div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, nextTick, onActivated } from 'vue';
import type { ComponentPublicInstance } from 'vue';
import {useRouter, useRoute} from 'vue-router';
import { Virtual } from 'swiper';
import { Swiper, SwiperSlide } from 'swiper/vue';
import type { Swiper as SwiperClass } from 'swiper/types';
import {getWxConfig} from '@/api/common';
import {getVideoCategoryList, saveVideoCategoryCollect} from '@/api/index';

import { useMainStore } from '@/store';
import showVip from '@/hooks/showVip';
import MyTabbar from '@/components/MyTabbar.vue';
import MyVideoPlay2 from '@/components/MyVideoPlay2.vue';
import MyDialogBtn from '@/components/MyDialogBtn.vue';
import {Toast} from 'vant';
import wx from 'weixin-jsapi';

const imgUrl = import.meta.env.VITE_IMG_URL;
const siteTitle = import.meta.env.VITE_SITE_TITLE;
const siteDomain = import.meta.env.VITE_DOMAIN;
const mainStore = useMainStore();
const router = useRouter();
const route = useRoute();
const state = reactive<any>({
  module:'category',//栏目
	showFlag: true,
  promote_contents:'点击右上角【...】分享到朋友圈或微信群',
	mobile: 'javascript:;',
	pageInfo: {
		pageIndex: 1,
		pageSize: 10,
	},
  payShow: false,
  vipShow: false,
  active: 0,
  currentIndex: 0,
	menberList: [] as any[],

  province: '',
  city: '',
  country: ''
});

onActivated(() => {
  if (state.menberList.length == 0) {
    state.pageInfo.user_id = mainStore.user_id;
    state.pageInfo.pageIndex = 1;
    state.menberList = [];
    getMemberList();
  } else {
    if (!mainStore.isUserDetailPath) {
      state.pageInfo.user_id = mainStore.user_id;
      state.pageInfo.pageIndex = 1;
      state.menberList = [];
      getMemberList();
    }
  }
});

// 视频点击
const videoClick = async () => {
	iframeRefs[currentItem.value.id].play();
};

// 收藏/取消收藏
const collect = async (like_user_id: number, index: number): Promise<any> => {
	const res = await saveVideoCategoryCollect(mainStore.user_id, like_user_id);
	Toast(res.errorInfo);
	const { is_collect, like_num } = state.menberList[index];
	const isCollect: boolean = res.data !== 1 ? false : true;
	state.menberList[index].is_collect = isCollect ? 0 : 1;
	state.menberList[index].like_num = isCollect ? like_num - 1 : like_num + 1;
};

// 分享
const initShare = async (update:boolean = false) => {
  const wxConfig = mainStore.wxConfig;
  console.log('wxConfig：',wxConfig)
  if (wxConfig == null || update) {
    const configRes = await getWxConfig();
    mainStore.wxConfig = configRes.data;
  }
  const { appId, timestamp, nonceStr, signature } = mainStore.wxConfig;
  let jsApiList = ['onMenuShareAppMessage', 'onMenuShareTimeline'];
  wx.config({
    debug: false,
    appId,
    timestamp,
    nonceStr,
    signature,
    jsApiList
  });
  wx.ready(() => {
    		wx.onMenuShareAppMessage({
    			title: siteTitle, // 分享标题
    			desc: `${currentItem.value.title}`, // 分享描述
    			link: `https://ztcy.huimaibuy.com/h5/#/category`, // 分享链接，该链接域名或路径必须与当前页面对应的公众号 JS 安全域名一致
    			imgUrl: mainStore.userInfo?.head_img_url, // 分享图标
    			type: 'link', // 分享类型,music、video或link，不填默认为link
    			dataUrl: '', // 如果 type 是music或video，则要提供数据链接，默认为空
    			success: async () => {
    				// 用户点击了分享后执行的回调函数
    			},
    			cancel: (res: any) => {
    				console.log(res);
    			}
    		});
    		wx.onMenuShareTimeline({
    			title: siteTitle, // 分享标题
    			link: `https://ztcy.huimaibuy.com/h5/#/category`, // 分享链接，该链接域名或路径必须与当前页面对应的公众号 JS 安全域名一致
    			imgUrl: mainStore.userInfo?.head_img_url, // 分享图标
    			success: async () => {
    				// 用户点击了分享后执行的回调函数
    			},
    			cancel: (res: any) => {
    				console.log(res);
    			}
    		});
  });
  wx.error((res:any) => {
    console.log('err', res)
  });
};

// 拨打电话
const callMobile = (mobile: string): any => {
  state.mobile = `tel:${mobile}`;
};

// 视频组件dom列表
interface IIframeRefs {
	[key: number | string]: any;
}
const iframeRefs: IIframeRefs = {};
const setItemRef = (el: Element | ComponentPublicInstance | null, key: number | string) => {
	if (el) {
		iframeRefs[key] = el;
	}
};

// 当前元素
const currentItem = computed<any>(() => state.menberList[state.currentIndex]);

// swiper 切换
let oldSwiperIndex = ref<number>(0);

let timer: NodeJS.Timeout | null = null;
const onSlideChange = (e: SwiperClass) => {
	if (timer) {
		clearTimeout(timer);
		timer = null;
	}
	timer = setTimeout(() => {
		// 加载更多
		if (e.activeIndex + 1 == state.menberList.length) {
			getMemberList();
		}

		state.currentIndex = e.activeIndex;
		// 重新加载当前视频
		if (currentItem.value && currentItem.value?.video_url) {
			nextTick(() => {
				iframeRefs[currentItem.value.id].videoRef.load();
			});
		}

		// 暂停上条视频
		const pvreItem = state.menberList[oldSwiperIndex.value];
		if (pvreItem && pvreItem.video_url) {
			nextTick(() => {
				iframeRefs[pvreItem.id].videoRef.pause();
			});
		}
		oldSwiperIndex.value = e.activeIndex;
		initShare();
	}, 500);
};

// 获取用户列表
const getMemberList = async () => {
  Toast.loading({
    message: '正在加载中',
    forbidClick: true,
  });
	const res = await getVideoCategoryList(state.pageInfo);
	if (res.data.dataList.length) {
		state.menberList = [...state.menberList, ...res.data.dataList];
		state.pageInfo.pageIndex++;
		await initShare(false);
	}
};
</script>

<style lang="scss" scoped>

:deep(.my_dialog_btn) {
  main {
    width: 285px;
    text-align: unset;
    .content_box {
      padding: 30px;
    }
  }
}

:deep(.van-tabs) {
  width: 100%;
  .van-tabs__wrap {
    height: 50px !important;
    .van-tabs__nav {
      justify-content: space-between;
      .van-tab {
        flex: auto;
        padding: 0;
        font-size: 16px;
      }
      .van-tab--active {
        font-size: 17px;
        font-weight: bold;
      }
    }

    .van-tabs__line {
      bottom: 20px;
      background: #f6438a;
    }
  }
}

:deep(.van-dropdown-menu) {
  .van-dropdown-menu__bar {
    box-shadow: none;
    background: white;
    .van-dropdown-menu__title {
      color: #f54386;
      font-size: 13px;
      &::after {
        border-color: transparent transparent #f54386 #f54386;
      }
    }
  }
  .van-popup--top {
    border-radius: 0 0 15px 15px;
  }
}
.matchmaker {
	padding: 0 15px;
  padding-top: 15px;
  //.header {
  //  @include flx-justify-between;
  //  height: 60px;
  //  .city {
  //    @include flx-align-center;
  //    height: 100%;
  //    span {
  //      font-size: 13px;
  //      margin-left: 2px;
  //    }
  //    .play {
  //      transform: rotate(90deg);
  //    }
  //  }
  //  .tabs {
  //    @include flx-center;
  //    height: 100%;
  //    width: 190px;
  //  }
  //}
	.my_swiper_box {
		.my_swiper {
			height: calc(100vh - 80px - env(safe-area-inset-bottom));
		}
		.swipe_item {
      .user_info {
        position: absolute;
        left: 15px;
        bottom: 30px;
        font-size: 18px;
        text-align: left;
        text-shadow: 2px 3px 6px #616060;
        width: 80%;
      }
			.img {
				height: calc(100vh - 80px - env(safe-area-inset-bottom));
			}
		}
	}
}
</style>
